package com.sskj.sys.service.impl;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.sskj.core.annotation.ControllerLogExeTime;
import com.sskj.core.exception.MException;
import com.sskj.sys.domain.entity.MediaEntity;
import com.sskj.sys.repository.MediaRepository;
import com.sskj.sys.vo.UploadFileVO;
import com.sskj.utils.CalendarUtil;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;

@RestController
@RequestMapping("/sys")
public class MediaServiceImpl {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Value("${sskj.conf.mediaUploadPath}")
	private String mediaUploadPath;

	@Autowired
	MediaRepository mediaRepository;

	@RequestMapping(value = "/img/getFiles", method = { RequestMethod.GET })
	public List<MediaEntity> queryFiles(String aId) throws MException {

		List<MediaEntity> results = mediaRepository.queryPic(aId);

		return results;
	}

	/** 删除附件 */
	@RequestMapping("/img/del")
	public void del(String id) {

		mediaRepository.delete(id);

		if (StringUtils.isNotEmpty(id)) {
			String[] idsArr = id.split(",");
			List<String> list = new ArrayList<String>();

			if (idsArr != null) {
				for (String idd : idsArr) {
					if (!idd.equals("ADMIN")) {
						list.add(idd);
					}
				}
				mediaRepository.delete(list);
			}
		}
	}

	@CrossOrigin
	@RequestMapping(value = "/img/upload", method = { RequestMethod.POST })
	@ControllerLogExeTime(description = "上传媒体数据")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "file", value = "图片", paramType = "form", required = true, dataType = "file") })
	public Map<String, Object> uploadImg(@RequestParam MultipartFile file) throws MException {

		String filename = file.getOriginalFilename();

		Map<String, Object> result = new HashMap<String, Object>();

		String path = CalendarUtil.dateToISO(Calendar.getInstance().getTime(), false) + "/"
				+ UUID.randomUUID().toString() + "/";

		File targetFile = new File(mediaUploadPath + path);
		// 生成图片保存的最终路径
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}

		try {
			FileUtils.copyInputStreamToFile(file.getInputStream(), new File(mediaUploadPath + path + filename));
			MediaEntity wme = new MediaEntity();
			wme.setMedianame(filename);
			wme.setHttpurl("upload/" + path + filename);
			wme.setMediasize(file.getSize());
			wme.setMediaurl(mediaUploadPath + path + filename);
			wme.setAssociatedentity("MediaEntity");
			mediaRepository.save(wme);
			result.put("obj", wme);
		} catch (IOException e) {
			e.printStackTrace();
			throw new MException("custom_msg", new Object[] { e.getMessage() });
		}

		return result;
	}

	@SuppressWarnings("static-access")
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/rich/upload", method = { RequestMethod.POST })
	@ControllerLogExeTime(description = "上传媒体数据")
	public String uploadRichImg(UploadFileVO file, HttpServletRequest request) throws MException {
		String fileBase64 = file.getMedataBase64();
		fileBase64 = fileBase64.substring(fileBase64.indexOf("base64,") + 7, fileBase64.length());
		// String path = mediaUploadPath;

		String filename = file.getFilename();

		String path = CalendarUtil.dateToISO(Calendar.getInstance().getTime(), false) + "/"
				+ UUID.randomUUID().toString() + "/";

		logger.info(path);

		File targetFile = new File(mediaUploadPath + path);
		// 生成图片保存的最终路径
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream out = null;
		String url = "";
		Base64 base64 = new Base64();
		try {
			// //Base64解码
			byte[] bytes = base64.decodeBase64(new String(fileBase64).getBytes());
			// byte[] bytes=fileBase64.getBytes();
			ByteArrayInputStream in = new ByteArrayInputStream(bytes);
			out = new FileOutputStream(mediaUploadPath + path + filename);
			byte[] buffer = new byte[1024];
			int byteread = 0;
			long alreadyRead = 0;
			int waitTime = 500;
			long daoTime = System.currentTimeMillis() + waitTime;
			request.getSession().setAttribute("uploadProgress", "0%");
			logger.info("进入了这里");
			while ((byteread = in.read(buffer)) != -1) {
				alreadyRead += byteread;
				if (System.currentTimeMillis() > daoTime) {
					logger.info("文件总大小：" + bytes.length + ",已经写入：" + alreadyRead + ",完成了"
							+ (alreadyRead / bytes.length * 100) + "%");
					request.getSession().setAttribute("uploadProgress", (alreadyRead / bytes.length * 100) + "%");
					daoTime = System.currentTimeMillis() + waitTime;
				}
				out.write(buffer, 0, byteread); // 文件写操作
				out.flush();
			}
			out.close();
			request.getSession().setAttribute("uploadProgress", "100%");
			logger.info("文件总大小：" + bytes.length + ",已经写入：" + alreadyRead + ",完成了" + (alreadyRead / bytes.length * 100)
					+ "%");

			// 将信息写入媒体entity
			MediaEntity wme = new MediaEntity();
			wme.setMedianame(filename);
			wme.setHttpurl("upload/" + path + filename);
			wme.setMediasize(bytes.length);
			wme.setMediaurl(mediaUploadPath + path + filename);
			wme.setAssociatedentity("MediaEntity");
			mediaRepository.save(wme);
			url = wme.getHttpurl();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new MException("custom_msg", new Object[] { e.getMessage() });
		} catch (IOException e) {
			e.printStackTrace();
			throw new MException("custom_msg", new Object[] { e.getMessage() });
		}
		return url;
	}

}
